package fr.dauphine.bookstore.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;

import fr.dauphine.bookstore.hibernate.HibernateUtil;

/**
 * Ouverture et fermeture d'une session Hibernate.
 */
public final class HibernateSessionFilter implements Filter {

	/**
	 * Loggeur.
	 */
	private static Log log = LogFactory.getLog(HibernateSessionFilter.class);

	/**
	 * Session factory.
	 */
	private SessionFactory sf;

	/**
	 * Execution du filtre.
	 * 
	 * @param request
	 *            Requete
	 * @param response
	 *            Reponse
	 * @param chain
	 *            Filtres suivants
	 * @throws ServletException
	 *             Erreur de servlet
	 * @throws IOException
	 *             Erreur d'entree/sortie
	 */
	public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
		try {
			sf.getCurrentSession().beginTransaction();

			// Call the next filter (continue request processing)
			chain.doFilter(request, response);

			// Commit and cleanup
			log.debug("Committing the database transaction");
			sf.getCurrentSession().getTransaction().commit();

		} catch (StaleObjectStateException staleEx) {
			log.error("This interceptor does not implement optimistic concurrency control!");
			log.error("Your application will not work until you add compensation actions!");
			// Rollback, close everything, possibly compensate for any permanent
			// changes
			// during the conversation, and finally restart business
			// conversation. Maybe
			// give the user of the application a chance to merge some of his
			// work with
			// fresh data... what you do here depends on your applications
			// design.
			throw staleEx;
		} catch (Throwable ex) {
			// Rollback only
			ex.printStackTrace();
			try {
				if (sf.getCurrentSession().getTransaction().isActive()) {
					log.debug("Trying to rollback database transaction after exception");
					sf.getCurrentSession().getTransaction().rollback();
				}
			} catch (Throwable rbEx) {
				log.error("Could not rollback transaction after exception!", rbEx);
			}

			// Let others handle it... maybe another interceptor for exceptions?
			throw new ServletException(ex);
		}
	}

	/**
	 * Destruction du filtre.
	 */
	public void destroy() {
	}

	/**
	 * Initialisation du filtre.
	 * 
	 * @param config
	 *            Configuration
	 * @throws ServletException
	 *             Erreur de servlet
	 */
	public void init(final FilterConfig config) throws ServletException {
		log.debug("Initializing filter...");
		log.debug("Obtaining SessionFactory from HibernateUtil");
		sf = HibernateUtil.getSessionFactory();
	}
}
